/*
 *  connection_window.cpp
 */

#include "client_app.h"
#include "client_window.h"
#include "connection_window.h"
#include "../../common/src/debug.h"
#include "../../common/src/lock.h"
#include "../../common/src/mutex.h"
#include "../../common/src/socket_exception.h"
#include "../../common/src/util.h"

ConnectionWindow::ConnectionWindow(BaseObjectType* object,
		                           const Glib::RefPtr<Gtk::Builder>& builder)
                                  :ClientWindow(object, builder) {
	builder->get_widget("IpEntry", eIP);
	builder->get_widget("PortEntry", ePort);
	builder->get_widget("UserNameEntry", eUserName);
	builder->get_widget("MessageLabel", lbMsg);
	builder->get_widget("ConnectButton", btnConnect);
	builder->get_widget_derived("LobbyWindow", winLobby);
	
    btnConnect->signal_clicked().connect(sigc::mem_fun(*this,
                                                 &ConnectionWindow::onConnect));
    eIP->set_text("127.0.0.1");
    ePort->set_text("2021");
    eUserName->set_text("Juan");
}

ConnectionWindow::~ConnectionWindow() {}

void ConnectionWindow::onConnect() {
    Lock lock(&mutex);
    if (app->isConnected()) return;
    std::string ipaddr = eIP->get_text();
    std::string port = ePort->get_text();
    std::string username = eUserName->get_text();
    if (ipaddr == "" || !Util::isipaddr(ipaddr.c_str())) {
        lbMsg->set_text("Error: invalid IP address");
    } else if (port == "" || !Util::isnum(port.c_str())) {
        lbMsg->set_text("Error: invalid port number");
    } else if (username == "") {
        lbMsg->set_text("Error: invalid username");
    } else {
        try {
            app->connect(username, ipaddr, Util::stoi(port));
            winLobby->show();
            get_application()->add_window(*winLobby);
            get_application()->remove_window(*this);
            hide();
        } catch (SocketException& e) {
            lbMsg->set_text("Error: Server connection failed");
        }
    }
}

void ConnectionWindow::setApp(ClientApp* app) {
    this->app = app;
    winLobby->setApp(app);
}

//{+}

